package io.renren.modules.app.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.common.exception.RRException;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;
import io.renren.modules.app.dao.BsEmployeeDao;
import io.renren.modules.app.dao.BsMemberDao;
import io.renren.modules.app.dao.BsProtocolDao;
import io.renren.modules.app.entity.*;
import io.renren.modules.app.service.BsProtocolService;
import io.renren.modules.sys.dao.SysUserDao;
import io.renren.modules.sys.dao.SysUserTokenDao;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;


@Service("bsProtocolService")
@Slf4j
public class BsProtocolServiceImpl extends ServiceImpl<BsProtocolDao, BsProtocolEntity> implements BsProtocolService {

    @Resource
    private BsProtocolDao bsProtocolDao ;

    @Resource
    private SysUserDao sysUserDao ;

    @Resource
    private BsMemberDao bsMemberDao ;

    @Resource
    private SysUserTokenDao sysUserTokenDao ;

    @Resource
    private BsEmployeeDao bsEmployeeDao ;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {

        LambdaQueryWrapper<BsProtocolEntity> wrapper3 = new LambdaQueryWrapper<>();
        if (params.get("protocolid") != null && !params.get("protocolid").toString().equals("")){
            wrapper3.like(BsProtocolEntity::getProtocolid,params.get("protocolid"));
        }
        if (params.get("memberName") != null && !params.get("memberName").toString().equals("")){
            LambdaQueryWrapper<BsMemberEntity> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.like(BsMemberEntity::getMemberName,params.get("memberName"));
            List<BsMemberEntity> bsMemberEntities = bsMemberDao.selectList(queryWrapper);
            List<String> list = new ArrayList<>();
            if (bsMemberEntities.size() > 0){
                for (BsMemberEntity bsMemberEntity : bsMemberEntities) {
                    list.add(bsMemberEntity.getMemberId());
                }
                wrapper3.in(BsProtocolEntity::getMemberId,list);
            }else {
                IPage<BsProtocolEntity> page = this.page(
                        new Query<BsProtocolEntity>().getPage(params),
                        new LambdaQueryWrapper<BsProtocolEntity>().eq(BsProtocolEntity::getId,-1)
                );
                return new PageUtils(page);
            }

        }
        if (params.get("userName") != null && !params.get("userName").toString().equals("")){
            LambdaQueryWrapper<BsEmployeeEntity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.like(BsEmployeeEntity::getEmployeeName,params.get("userName"));
            List<BsEmployeeEntity> sysUserEntities = bsEmployeeDao.selectList(lambdaQueryWrapper);
            List<String> list = new ArrayList<>();
            if (sysUserEntities.size() > 0){
                for (BsEmployeeEntity sysUserEntity : sysUserEntities) {
                    list.add(sysUserEntity.getEmployeeId().toString());
                }
                wrapper3.in(BsProtocolEntity::getSignuserId,list);
            }else {
                IPage<BsProtocolEntity> page = this.page(
                        new Query<BsProtocolEntity>().getPage(params),
                        new LambdaQueryWrapper<BsProtocolEntity>().eq(BsProtocolEntity::getId, -1)
                );
                return new PageUtils(page);
            }
        }
        if (params.get("memberPhone") != null && !params.get("memberPhone").toString().equals("")){
            LambdaQueryWrapper<BsMemberEntity> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.like(BsMemberEntity::getMemberPhone,params.get("memberPhone"));
            List<BsMemberEntity> bsMemberEntities = bsMemberDao.selectList(queryWrapper);
            List<String> list = new ArrayList<>();
            if (bsMemberEntities.size() > 0){
                for (BsMemberEntity bsMemberEntity : bsMemberEntities) {
                    list.add(bsMemberEntity.getMemberId());
                }
                wrapper3.in(BsProtocolEntity::getMemberId,list);
            }else {
                IPage<BsProtocolEntity> page = this.page(
                        new Query<BsProtocolEntity>().getPage(params),
                        new LambdaQueryWrapper<BsProtocolEntity>().eq(BsProtocolEntity::getId, -1)
                );
                return new PageUtils(page);
            }
        }


        IPage<BsProtocolEntity> page = this.page(
                new Query<BsProtocolEntity>().getPage(params),
                wrapper3
        );

        for (BsProtocolEntity record : page.getRecords()) {
            //会员姓名数据清洗
            LambdaQueryWrapper<BsMemberEntity> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(BsMemberEntity::getMemberId,record.getMemberId());
            List<BsMemberEntity> bsMemberEntities = bsMemberDao.selectList(wrapper);
            if (bsMemberEntities.size() == 1){
                record.setMemberName(bsMemberEntities.get(0).getMemberName());
                record.setMemberSex(bsMemberEntities.get(0).getMemberSex());
                record.setMemberAge(bsMemberEntities.get(0).getMemberAge().toString());
                record.setMemberPhone(bsMemberEntities.get(0).getMemberPhone());
            }
            //营销人员姓名数据清洗
            LambdaQueryWrapper<BsEmployeeEntity> wrapper1 = new LambdaQueryWrapper<>();
            wrapper1.eq(BsEmployeeEntity::getEmployeeId,record.getSignuserId());
            List<BsEmployeeEntity> userEntityList = bsEmployeeDao.selectList(wrapper1);
            if (userEntityList.size() == 1){
                record.setUserName(userEntityList.get(0).getEmployeeName());
            }
            //合同审批人数据清洗
            LambdaQueryWrapper<BsEmployeeEntity> wrapper2 = new LambdaQueryWrapper<>();
            wrapper2.eq(BsEmployeeEntity::getEmployeeId,record.getApprovalUser());
            List<BsEmployeeEntity> sysUserEntities = bsEmployeeDao.selectList(wrapper2);
            if (sysUserEntities.size() == 1){
                record.setApprovalUserName(sysUserEntities.get(0).getEmployeeName());
            }


        }

        return new PageUtils(page);
    }

    @Override
    public synchronized void saveProtocol(BsProtocolEntity bsProtocol, HttpServletRequest request) {
        try {
            //会员编号存在性校验
            LambdaQueryWrapper<BsMemberEntity> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(BsMemberEntity::getMemberId,bsProtocol.getMemberId());
            List<BsMemberEntity> entities = bsMemberDao.selectList(wrapper);
            if (entities.size() < 1){
                throw new RRException("会员编号不合法");
            }
            //营销人员姓名校验
            LambdaQueryWrapper<BsEmployeeEntity> wrapper1 = new LambdaQueryWrapper<>();
            wrapper1.eq(BsEmployeeEntity::getEmployeeId,bsProtocol.getUserName());
            List<BsEmployeeEntity> entities1 = bsEmployeeDao.selectList(wrapper1);
            if (entities1.size() < 1){
                throw new RRException("营销人员姓名不合法");
            }
            bsProtocol.setSignuserId(entities1.get(0).getEmployeeId().toString());

            //日期校验
            Date signDate = bsProtocol.getSignDate(); //签订日期
            Date signdateBegin = bsProtocol.getSigndateBegin();//生效开始日期
            Date signdateEnd = bsProtocol.getSigndateEnd();//生效结束日期
            if (signDate.getTime() > signdateBegin.getTime()){
                throw new RRException("合同签订时间不能大于合同生效开始时间");
            }
            if (signDate.getTime() > signdateEnd.getTime()){
                throw new RRException("合同签订时间不能大于合同生效结束时间");
            }
            if (signdateBegin.getTime() > signdateEnd.getTime()){
                throw new RRException("合同生效开始时间不能大于合同生效结束时间");
            }
            //生成唯一合同编号  uuid+时间戳
            String time = String.valueOf(new Date().getTime());
            String uuid = UUID.randomUUID().toString().replace("-","");
            String protoid = time + uuid ;
            bsProtocol.setProtocolid(protoid);
            //若合同选择已生效，那么审批人给上
            if ("生效".equals(bsProtocol.getVaild())){
//                String token = request.getHeader("token");
//                Long userId = sysUserTokenDao.queryByToken(token).getUserId();
                bsProtocol.setApprovalUser(entities1.get(0).getEmployeeId().toString());
            }
            bsProtocolDao.insert(bsProtocol);
        }catch (Exception e){
            log.info("报错所在的类及方法：{}","BsProtocolService --> saveProtocol");
            log.info(e.getMessage());
            throw new RRException(e.getMessage());
        }
    }

    @Override
    public BsProtocolEntity getprotoById(Long id) {
        BsProtocolEntity entity = bsProtocolDao.selectById(id);
        //营销人员姓名
        LambdaQueryWrapper<BsEmployeeEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(BsEmployeeEntity::getEmployeeId,entity.getSignuserId());
        List<BsEmployeeEntity> entities = bsEmployeeDao.selectList(wrapper);
        if (entities.size() == 1){
            entity.setUserName(entities.get(0).getEmployeeId());
        }
        //合同审批人姓名
        LambdaQueryWrapper<BsEmployeeEntity> wrapper1 = new LambdaQueryWrapper<>();
        wrapper.eq(BsEmployeeEntity::getEmployeeId,entity.getApprovalUser());
        List<BsEmployeeEntity> entities1 = bsEmployeeDao.selectList(wrapper1);
        if (entities1.size() == 1){
            entity.setApprovalUserName(entities1.get(0).getEmployeeId());
        }
        return entity;
    }

    @Override
    public void updateProtocolById(BsProtocolEntity bsProtocol,HttpServletRequest request) {
        try {
            //会员编号存在性校验
            LambdaQueryWrapper<BsMemberEntity> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(BsMemberEntity::getMemberId,bsProtocol.getMemberId());
            List<BsMemberEntity> entities = bsMemberDao.selectList(wrapper);
            if (entities.size() < 1){
                throw new RRException("会员编号不合法");
            }
            BsProtocolEntity bsProtocolEntity = bsProtocolDao.selectById(bsProtocol.getId());
            if (!bsProtocolEntity.getMemberId().equals(bsProtocol.getMemberId())){
                throw new RRException("会员编号不允许修改");
            }
            //营销人员姓名校验
            LambdaQueryWrapper<BsEmployeeEntity> wrapper1 = new LambdaQueryWrapper<>();
            wrapper1.eq(BsEmployeeEntity::getEmployeeId,bsProtocol.getUserName());
            List<BsEmployeeEntity> entities1 = bsEmployeeDao.selectList(wrapper1);
            if (entities1.size() < 1){
                throw new RRException("营销人员姓名不合法");
            }
            bsProtocol.setSignuserId(entities1.get(0).getEmployeeId().toString());

            //日期校验
            Date signDate = bsProtocol.getSignDate(); //签订日期
            Date signdateBegin = bsProtocol.getSigndateBegin();//生效开始日期
            Date signdateEnd = bsProtocol.getSigndateEnd();//生效结束日期
            if (signDate.getTime() > signdateBegin.getTime()){
                throw new RRException("合同签订时间不能大于合同生效开始时间");
            }
            if (signDate.getTime() > signdateEnd.getTime()){
                throw new RRException("合同签订时间不能大于合同生效结束时间");
            }
            if (signdateBegin.getTime() > signdateEnd.getTime()){
                throw new RRException("合同生效开始时间不能大于合同生效结束时间");
            }
            //若合同选择已生效，那么审批人给上
            if ("生效".equals(bsProtocol.getVaild())){
//                String token = request.getHeader("token");
//                Long userId = sysUserTokenDao.queryByToken(token).getUserId();
//                bsProtocol.setApprovalUser(userId.toString());
                bsProtocol.setApprovalUser(entities1.get(0).getEmployeeId().toString());
            }
            bsProtocolDao.updateById(bsProtocol);
        }catch (Exception e){
            log.info("报错所在的类及方法：{}","BsProtocolService --> updateProtocolById");
            log.info(e.getMessage());
            throw new RRException(e.getMessage());
        }
    }

    @Override
    public List<QuarterProtocolDto> quarterProtocol() {
        List<QuarterProtocolDto> quarterProtocolDto = null ;
     try {
         quarterProtocolDto = bsProtocolDao.quarterProtocol();
     }catch (Exception e){
         log.info("报错所在的类及方法：{}","BsProtocolService --> quarterProtocol");
         log.info(e.getMessage());
     }
     return  quarterProtocolDto;
    }

    @Override
    public List<QuarterProtocolDto> quarterIntendCustomer() {
        List<QuarterProtocolDto> quarterProtocolDto = null ;
        try {
            quarterProtocolDto = bsProtocolDao.quarterIntendCustomer();
        }catch (Exception e){
            log.info("报错所在的类及方法：{}","BsProtocolService --> quarterIntendCustomer");
            log.info(e.getMessage());
        }
        return quarterProtocolDto ;
    }

    @Override
    public List<QuarterProtocolDto> quarterProtocolSignUser() {
        List<QuarterProtocolDto> quarterProtocolDto = null ;
        List<QuarterProtocolDto> list = new ArrayList<>() ; //季度销冠人员集合
        Map<String,String> map = new HashMap<>() ; //返回数据， key为季度
        List<QuarterProtocolDto> listDto = new ArrayList<>(); //最终返回数据
        try {
            quarterProtocolDto = bsProtocolDao.quarterProtocolSignUser();
            //只取每个季度销冠人员
            //若出现并列销冠那么需要进行数据处理

            //根据季度将集合进行分组 list--》map
            Map<String, List<QuarterProtocolDto>> collect = quarterProtocolDto.stream().collect(Collectors.groupingBy(QuarterProtocolDto::getQuarter));
            for (Map.Entry<String, List<QuarterProtocolDto>> stringListEntry : collect.entrySet()) {
                int num = 0 ; //收集每个季度销冠所签订合同数量
                for (QuarterProtocolDto dto : stringListEntry.getValue()) {
                    if (dto.getNum() > num){
                        num = dto.getNum() ; //进行合同数量比较，进行收集数据
                    }
                }
                for (QuarterProtocolDto protocolDto : stringListEntry.getValue()) {
                    if (protocolDto.getNum() == num){
                        list.add(protocolDto) ; //拿到每个季度销冠对象，并列销冠同样进行收集
                    }
                }
            }
            //拿到销冠对象，可能某个季度有多个并列销冠
            for (QuarterProtocolDto protocolDto : list) {
                switch (protocolDto.getQuarter()){
                    case "1" :
                        String s1 = map.get("1"); //拿到第一季度对应value值
                        if (StringUtils.isNotBlank(s1)){
                            map.put("1",s1 + "," + protocolDto.getSignUser() + "-" + protocolDto.getNum());
                        }else {
                            map.put("1",protocolDto.getSignUser() + "-" + protocolDto.getNum());
                        }
                        continue;
                    case "2" :
                        String s2 = map.get("2"); //拿到第二季度对应value值
                        if (StringUtils.isNotBlank(s2)){
                            map.put("2",s2 + "," + protocolDto.getSignUser() + "-" + protocolDto.getNum());
                        }else {
                            map.put("2",protocolDto.getSignUser() + "-" + protocolDto.getNum());
                        }
                        continue;
                    case "3" :
                        String s3 = map.get("3"); //拿到第二季度对应value值
                        if (StringUtils.isNotBlank(s3)){
                            map.put("3",s3 + "," + protocolDto.getSignUser() + "-" + protocolDto.getNum());
                        }else {
                            map.put("3",protocolDto.getSignUser() + "-" + protocolDto.getNum());
                        }
                        continue;
                    case "4" :
                        String s4 = map.get("4"); //拿到第二季度对应value值
                        if (StringUtils.isNotBlank(s4)){
                            map.put("4",s4 + "," + protocolDto.getSignUser() + "-" + protocolDto.getNum());
                        }else {
                            map.put("4",protocolDto.getSignUser() + "-" + protocolDto.getNum());
                        }
                        continue;
                }
            }
            //对map进行处理
            for (Map.Entry<String, String> stringStringEntry : map.entrySet()) {
                if ("1".equals(stringStringEntry.getKey())){
                    String value = stringStringEntry.getValue();
                    String[] split = value.split(",");
                    String indexNum = split[0].split("-")[1];
                    QuarterProtocolDto dto = new QuarterProtocolDto() ;
                    dto.setQuarter("1");
                    dto.setNum(Integer.valueOf(indexNum));
                    String user = "";
                    for (QuarterProtocolDto protocolDto : list) {
                        if (protocolDto.getQuarter().equals("1")){
                            LambdaQueryWrapper<BsEmployeeEntity> wrapper = new LambdaQueryWrapper<>();
                            wrapper.eq(BsEmployeeEntity::getEmployeeId,protocolDto.getSignUser());
                            if (bsEmployeeDao.selectList(wrapper).size() > 0){
                                String employeeName = bsEmployeeDao.selectList(wrapper).get(0).getEmployeeName();
                                if (StringUtils.isNotBlank(user)){
                                    String concat = user.concat("," + employeeName);
                                    user = concat ;
                                }else {
                                    user = employeeName;
                                }
                            }else {
                                if (StringUtils.isNotBlank(user)){
                                    String concat = user.concat("," + protocolDto.getSignUser());
                                    user = concat ;
                                }else {
                                    user = protocolDto.getSignUser();
                                }
                            }
                        }
                    }
                    dto.setSignUser(user);
                    listDto.add(dto);
                }else if ("2".equals(stringStringEntry.getKey())){
                    String value = stringStringEntry.getValue();
                    String[] split = value.split(",");
                    String indexNum = split[0].split("-")[1];
                    QuarterProtocolDto dto = new QuarterProtocolDto() ;
                    dto.setQuarter("2");
                    dto.setNum(Integer.valueOf(indexNum));
                    String user = "";
                    for (QuarterProtocolDto protocolDto : list) {
                        if (protocolDto.getQuarter().equals("2")){
                            LambdaQueryWrapper<BsEmployeeEntity> wrapper = new LambdaQueryWrapper<>();
                            wrapper.eq(BsEmployeeEntity::getEmployeeId,protocolDto.getSignUser());
                            if (bsEmployeeDao.selectList(wrapper).size() > 0){
                                String employeeName = bsEmployeeDao.selectList(wrapper).get(0).getEmployeeName();
                                if (StringUtils.isNotBlank(user)){
                                    String concat = user.concat("," + employeeName);
                                    user = concat ;
                                }else {
                                    user = employeeName;
                                }
                            }else {
                                if (StringUtils.isNotBlank(user)){
                                    String concat = user.concat("," + protocolDto.getSignUser());
                                    user = concat ;
                                }else {
                                    user = protocolDto.getSignUser();
                                }
                            }

                        }
                    }
                    dto.setSignUser(user);
                    listDto.add(dto);
                }else if ("3".equals(stringStringEntry.getKey())){
                    String value = stringStringEntry.getValue();
                    String[] split = value.split(",");
                    String indexNum = split[0].split("-")[1];
                    QuarterProtocolDto dto = new QuarterProtocolDto() ;
                    dto.setQuarter("3");
                    dto.setNum(Integer.valueOf(indexNum));
                    String user = "";
                    for (QuarterProtocolDto protocolDto : list) {
                        if (protocolDto.getQuarter().equals("3")){
                            LambdaQueryWrapper<BsEmployeeEntity> wrapper = new LambdaQueryWrapper<>();
                            wrapper.eq(BsEmployeeEntity::getEmployeeId,protocolDto.getSignUser());
                            if (bsEmployeeDao.selectList(wrapper).size() > 0){
                                String employeeName = bsEmployeeDao.selectList(wrapper).get(0).getEmployeeName();
                                if (StringUtils.isNotBlank(user)){
                                    String concat = user.concat("," + employeeName);
                                    user = concat ;
                                }else {
                                    user = employeeName;
                                }
                            }else {
                                if (StringUtils.isNotBlank(user)){
                                    String concat = user.concat("," + protocolDto.getSignUser());
                                    user = concat ;
                                }else {
                                    user = protocolDto.getSignUser();
                                }
                            }

                        }
                    }
                    dto.setSignUser(user);
                    listDto.add(dto);
                }else {
                    String value = stringStringEntry.getValue();
                    String[] split = value.split(",");
                    String indexNum = split[0].split("-")[1];
                    QuarterProtocolDto dto = new QuarterProtocolDto() ;
                    dto.setQuarter("4");
                    dto.setNum(Integer.valueOf(indexNum));
                    String user = "";
                    for (QuarterProtocolDto protocolDto : list) {
                        if (protocolDto.getQuarter().equals("4")){
                            LambdaQueryWrapper<BsEmployeeEntity> wrapper = new LambdaQueryWrapper<>();
                            wrapper.eq(BsEmployeeEntity::getEmployeeId,protocolDto.getSignUser());
                            if (bsEmployeeDao.selectList(wrapper).size() > 0){
                                String employeeName = bsEmployeeDao.selectList(wrapper).get(0).getEmployeeName();
                                if (StringUtils.isNotBlank(user)){
                                    String concat = user.concat("," + employeeName);
                                    user = concat ;
                                }else {
                                    user = employeeName;
                                }
                            }else {
                                if (StringUtils.isNotBlank(user)){
                                    String concat = user.concat("," + protocolDto.getSignUser());
                                    user = concat ;
                                }else {
                                    user = protocolDto.getSignUser();
                                }
                            }

                        }
                    }
                    dto.setSignUser(user);
                    listDto.add(dto);
                }
            }
            System.out.println(list);

        }catch (Exception e){
            e.printStackTrace();
            log.info("报错所在的类及方法：{}","BsProtocolService --> quarterProtocolSignUser");
            log.info(e.getMessage());
        }
        return  listDto;
    }

    @Override
    public List<BsAllMemberVo> queryAllMember() {
        return bsProtocolDao.queryAllMember();
    }

    @Override
    public List<BsAllEmployeeVo> queryAllEmployee() {
        return bsProtocolDao.queryAllEmployee();
    }
}
